﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using System.IO;

namespace sfsocket.corelib.message
{
    /// <summary>
    /// Ping is a LTV message, but without Value 
    /// 0x00000006  - length = 4
    /// 0x00000001  - type (4byte)
    /// </summary>
    public class PongMessage : BaseMessage
    {
        /// <summary>
        /// ping message 
        /// </summary>
        public PongMessage()
        {
            this.Length = 4;
            this.MessageType = (int)MessageTypeEnum.PONG; 
        }

        public static PongMessage Parse(byte[] _headerBuf)
        {
            PongMessage msg = new PongMessage();
            if (_headerBuf == null)
                return null;

            Stream memStream = new MemoryStream(_headerBuf);
            BinaryReader reader = new BinaryReader(memStream);

            msg.Length = IPAddress.NetworkToHostOrder(reader.ReadInt32());

            // validate the packet 
            if (msg.Length != _headerBuf.Length - 4)
            {
                msg = null;
                throw new ArgumentException("invalid packet! length is not valid!");
            }

            msg.MessageType = IPAddress.NetworkToHostOrder(reader.ReadInt32());

            return msg;
        }

        public override byte[] GetBytes()
        {
            byte[] buff = new byte[Length + 4];
            Stream memStream = new MemoryStream(buff);
            BinaryWriter writer = new BinaryWriter(memStream);
            writer.Write(IPAddress.HostToNetworkOrder(Length));
            writer.Write(IPAddress.HostToNetworkOrder(MessageType));
            writer.Close();
            memStream.Close();
            return buff;
		}


    }


    public class PongMsgUnitTest
    {
        public static void TestConstruction()
        {
            Console.WriteLine("TestConstruction");
            PongMessage ping = new PongMessage();
            ping.Dump();
            foreach (byte b in ping.GetBytes())
            {
                Console.Write("0x{0:X}, ", b);
            }
            Console.WriteLine();

            PongMessage msg2 = PongMessage.Parse(ping.GetBytes());
            msg2.DumpHex();
        }
    }
}
